package ar.edu.itba.bundundu;

import java.io.IOException;
import java.net.URL;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.itba.bundundu.dao.UserDao;
import ar.edu.itba.bundundu.domain.UserIds;

import com.google.code.facebookapi.FacebookParam;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.calendar.CalendarAclRole;

public class AddAccessServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    RequestDispatcher dispatcher;
    dispatcher = getServletContext().getRequestDispatcher("/sharecalendars");
    try {

      Facebook facebook = new Facebook(req
          .getParameter(FacebookParam.SESSION_KEY.toString()));
      Long uid = facebook.getUserId();
      String uids = facebook.getUidsAppFriends();
      req.setAttribute("uid", uid);
      req.setAttribute("uids", uids);
      UserIds user = UserDao.getUser(uid);
      String sessionToken = user.getToken();
      CalendarService service = new CalendarService("exampleCo-exampleApp-1");
      service.setAuthSubToken(sessionToken, null);
      // get the params from the form
      String friend_uid = (String) req.getParameter("friend_sel");
      Integer level = Integer.valueOf((String) req.getParameter("level"));
      String calendar_url = (String) req.getParameter("calendar_url");
      if (friend_uid != null) {
        UserIds friend = UserDao.getUser(Long.valueOf(friend_uid));
        AclEntry entry = new AclEntry();
        entry.setScope(new AclScope(AclScope.Type.USER, friend.getEmail()));
        switch (level) {
        case 1:
          entry.setRole(CalendarAclRole.OWNER);
          break;
        case 2:
          entry.setRole(CalendarAclRole.EDITOR);
          break;
        case 3:
          entry.setRole(CalendarAclRole.READ);
          break;
        case 4:
          entry.setRole(CalendarAclRole.FREEBUSY);
          break;
        default: // error
        }
        calendar_url = "http://www.google.com/calendar/feeds/"
            + calendar_url
                .substring("http://www.google.com/calendar/feeds/default/calendars/"
                    .length()) + "/acl/full";
        URL aclUrl = new URL(calendar_url);
        try {
          AclEntry insertedEntry = service.insert(aclUrl, entry);
          String name = (String) req.getParameter("calendar_name");
          req.setAttribute("success", "You are now sharing " + "<strong>"
              + name + "</strong>" + " with <fb:name uid=\"" + friend.getUid()
              + "\" capitalize=\"true\" />");
          req.setAttribute("calendar_name", name);
          req.setAttribute("calendar_friend", friend.getUid());
        } catch (Exception e) {
          req
              .setAttribute(
                  "error",
                  "Oops! an error has occurred. Please, try again later."
                      + "  Or check if you are not already sharing that calendar with your friend.");
        }
      }
      dispatcher.forward(req, resp);
    } catch (Exception e) {
      req.setAttribute("error", e.getMessage());
      //e.printStackTrace();
      dispatcher.forward(req, resp);
    }
  }
}
